package com.shchekoldin.juliet.packager.plugins;

import com.shchekoldin.juliet.packager.core.Packager;
import com.shchekoldin.juliet.packager.utils.FilesIterator;
import com.shchekoldin.juliet.packager.utils.FilesIteratorEvent;
import com.shchekoldin.juliet.packager.xml.GroupElement;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;

public class FilesAssembler implements PackagerPlugin {

    private static final Logger logger = LoggerFactory.getLogger(FilesAssembler.class);

    private OutputStreamWriter fileWriter;

    // -------------------------------------------------------
    // -                        LOGIC                        -
    // -------------------------------------------------------

    private void subscribeOnFilesIteratorEvents(final FilesIterator filesIterator) {
        filesIterator.getOnIterate().add(new FilesIteratorEvent() {
            @Override
            public void run() { addContent(filesIterator.getCurrentFileContent()); }
        });

        filesIterator.getOnFinish().add(new FilesIteratorEvent() {
            @Override
            public void run() { finish(); }
        });
    }

    private void addContent(String fileContent) {
        try {
            fileWriter.append(fileContent);
        } catch (IOException e) {
            logger.error("Can't add content to assembled file", e);
            Packager.getInstance().exit();
        }
    }

    private void finish() {
        try {
            fileWriter.close();
        } catch (IOException e) {
            logger.error("Can't close assembled file", e);
            Packager.getInstance().exit();
        }
    }

    //
    // API
    //

    @Override
    public void initialize(FilesIterator filesIterator) {
        GroupElement group = filesIterator.getGroup();

        if (group.getIncludeFiles().size() == 0) {
            // Nothing to assemble.
            return;
        }

        try {
            FileOutputStream fileStream = new FileOutputStream(group.getOutputDir() + group.getName()
                + group.getFilesExtension());
            fileWriter = new OutputStreamWriter(fileStream, "utf-8");
        } catch (IOException e) {
            logger.error("Can't create assembled file", e);
            Packager.getInstance().exit();
        }

        subscribeOnFilesIteratorEvents(filesIterator);
    }

}
